import webview
import os
import json
import subprocess
import hashlib
from InitNas import InitNas
from NasData import NasData
from FmsCommon import FmsCommon
import datetime


class Api():
    def __init__(self):
        fc =FmsCommon()
        self.my_dir_path_h  = fc.my_dir_path_h
        self.root_dir  = fc.root_dir
        self.load_file_name  = fc.load_file_name
        self.my_dir_path = fc.my_dir_path

    def openFileFromExplorer(self,file_path):
        
        subprocess.run(['explorer', '/select,', os.path.abspath(file_path)])

    def getSltKeySearch(self, param):

        
        nData = NasData()
        data = {"root_dir":self.root_dir,"files":nData.getSltKeySearch(param)}
        return data

    def getNasInfosByFolder(self, nas_abs_folder_path):
        nData = NasData()
        return nData.getNasInfosByFolder(nas_abs_folder_path)
    def getNasInfosBySame(self, nas_abs_file_path):
        
        nData = NasData()
        return nData.getNasInfosBySame(nas_abs_file_path)
    
    def addNasInfos(self, items):
        for item in items:
            self.addNasInfo(item)
    def addNasInfo(self, item):
        nData = NasData()
        nData.addNasInfo(item)


    def getNasFileExt(self):
        nData = NasData()
        p  = nData.getNasFileExt()
        
        return p
        
        
    def get_file_md5(self,file_path):
        md5_hash = hashlib.md5()
        with open(file_path, 'rb') as file:
            for chunk in iter(lambda: file.read(4096), b""):
                md5_hash.update(chunk)
        return md5_hash.hexdigest()
    
    def getTree3(self, folder_path0):
        
        install_date = datetime.datetime(2027, 1, 1)
        validity_period = datetime.timedelta(days=30)

        expiration_date = install_date + validity_period
        current_date = datetime.datetime.now()

        if current_date > expiration_date:
            # 过期
            m = self.get_file_md5(self.my_dir_path_h+"/template/index.htm")
            # m = self.get_file_md5(self.my_dir_path+"/template/index.htm")
            # if m!='c92949d6c83a0dccaaea9e886f3de1a4':
            #     return ""
            # m = self.get_file_md5(self.my_dir_path+"/template/index.js")
            # if m!='c92949d6c83a0dccaaea9e886f3de1a4':
            #     return ""
            # m = self.get_file_md5(self.my_dir_path+"/template/data.js")
            # if m!='c92949d6c83a0dccaaea9e886f3de1a4':
            #     return ""
            return ""
            


        self.id = 1
        folder_path = self.my_dir_path+"\\"+folder_path0

        self.tree_data = [{"title": folder_path0, "spread": True, "id": self.id,
                           "path": "\\"+folder_path0, "abs_path": folder_path, "children": []}]

        for root, dirs, files in os.walk(folder_path):
            for file_name in dirs:
                if file_name != "_raw":
                    self.id = self.id + 1
                    abs_file_path = os.path.join(root, file_name)
                    substring = abs_file_path[len(self.my_dir_path):]
                    self.make_tree_xml(substring)
        data = json.dumps(self.tree_data)
        
        return data

    def make_tree_xml(self, abs_file_path):
        nodes = abs_file_path.split("\\")
        tree_data = self.tree_data
        children = tree_data[0]["children"]
        for i in range(2, len(nodes)):
            children = self.getChildren(children, nodes[i], abs_file_path)

    def getChildren(self, children, title, abs_file_path):
        for child in children:
            if child["title"] == title:
                return child["children"]
        folder_path = self.my_dir_path+abs_file_path
        tag = {"title": title, "spread": False, "id": self.id,
               "path": abs_file_path, "abs_path": folder_path, "children": []}
        children.append(tag)
        return tag["children"]
    def delFile(self,nas_abs_file_path,nas_abs_file_raw_path):
        nData = NasData()
        nData.delNasInfo(nas_abs_file_path)
        if os.path.exists(nas_abs_file_path):        
            os.remove(nas_abs_file_path)
        if os.path.exists(nas_abs_file_raw_path):
            os.remove(nas_abs_file_raw_path)
        return True
    def getFile(self, folder_path):
        
        entries = os.listdir(folder_path)

        # 过滤出只包含文件名的列表
        files = [f for f in entries if os.path.isfile(
            os.path.join(folder_path, f))]

        for file in files:
            self.load_file_name = file
            inas = InitNas()
            inas.create_raw(folder_path,file)
        nData = NasData()
        

        data = {"root_dir":self.root_dir,"files":nData.getNasInfosByFolder(folder_path)}

        return data

    def getLoadFileName(self):
        return self.load_file_name
    def safeFolderPwd(self,pwd):
        return pwd=="741852"
   

        

class Fms():
    def __init__(self):
        current_file_path = os.path.abspath(
            globals().get('__file__', os.getcwd()))
        self.my_dir_path = os.path.dirname(current_file_path)
        self.root_dir = os.path.abspath(os.sep)
        pass
    
    def main(self):
        url = f"file://{self.my_dir_path}/template/index.htm"

        window  = webview.create_window('文件管理', url, width=1400,
                              height=600, resizable=True, js_api=Api())
        
        webview.start(debug=True)


if __name__ == "__main__":

    fms = Fms()
    fms.main()
